"""
threading.Lock() # 创建一个锁对象
lock.acquire() # 获取锁
lock.release() # 释放锁
注意: with lock: 自动的获取锁和释放锁
"""
import threading
# 共享资源
balance = 100
# 创建锁
lock = threading.Lock()
def func1(num):
    global balance
    # with lock: # 自动的获取锁和释放锁
    #     old_balance = balance
    #     balance += num
    #     print(f"存钱:{old_balance}+{num}={balance}")
    lock.acquire()
    old_balance = balance
    balance += num
    print(f"存钱:{old_balance}+{num}={balance}")
    lock.release()
def func2(num):
    global balance
    # with lock: # 自动的获取锁和释放锁
    #     old_balance = balance
    #     balance -= num
    #     print(f"取钱:{old_balance}-{num}={balance}")
    lock.acquire()
    old_balance = balance
    balance -= num
    print(f"取钱:{old_balance}-{num}={balance}")
    lock.release()
if __name__ == '__main__':
    # 创建多个存取钱线程
    threads = [
        threading.Thread(target=func1,args=(50,)),
        threading.Thread(target=func2,args=(30,)),
        threading.Thread(target=func1,args=(100,)),
        threading.Thread(target=func2,args=(20,)),
    ]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print("最终的余额为:",balance)









